package com.jiuzhou.crawlers.taobao.processor.taobao.urlstrategy.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import com.jiuzhou.common.SpringContextUtil;
import com.jiuzhou.crawler.entity.taobao.GoodsKeyWords;
import com.jiuzhou.crawler.taobao.mapper.KeyWordsDao;
import com.jiuzhou.crawlers.taobao.processor.taobao.constant.CommonConstant;
import com.jiuzhou.crawlers.taobao.processor.taobao.urlstrategy.ITaobaoTypeObtainStrategy;
import com.jiuzhou.services.taobao.IKeyWordsService;
import com.jiuzhou.services.taobao.impl.KeyWordsImpl;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Json;


@Component
public class TypeStrategyImpl implements  ITaobaoTypeObtainStrategy{
    
   private static IKeyWordsService keyservice;  
     
   //在线程中加载spring bean
   static{  
	   keyservice = (IKeyWordsService)SpringContextUtil.getBean("classpath:/service.xml", "keyWordsService");
   }
   
	/**方法名称：getTypeByAllSorts()
	 * 方法说明：类型获取url:https://www.taobao.com/tbhome/page/market-list?spm=a21bo.50862.1997563209.1.l6tdql
	 */
	@Override
	public void getTypeByAllSorts(Page page) {
		//使用品分类爬取
		if(page.getHtml().css("div.category-items").xpath("//a/text()").all().size()>0){ //判断爬取网页的标志
			//List<String> titleKey = page.getHtml().xpath("//a[@class='category-name-level1']/text()").all();
			 CommonConstant.GOODSTYPE  = page.getHtml().xpath("//a[@class='category-name']/text()").all();
			 //将关键词存于数据库
			    for(String keyword : CommonConstant.GOODSTYPE){
				    GoodsKeyWords goodsKeyWords = new GoodsKeyWords();
				    goodsKeyWords.setDownload_state("success");
				    goodsKeyWords.setKeyword(keyword);
				    goodsKeyWords.setUrl(page.getUrl().toString());
				    keyservice.insert(goodsKeyWords);
			    }
			 
			 for(	int i  = 0 ; i <CommonConstant.GOODSTYPE .size() ;  i++){
				  if(CommonConstant.GOODSTYPE.get(i).equals("")){
					  CommonConstant.GOODSTYPE.remove(i);
				  }
			 }
		     int goodis = 0;
		     for(int id = 0 ; id <  CommonConstant.GOODSTYPE .size() ;id++ ){
		    	 if(  CommonConstant.GOODSTYPE .get(id).trim().equals(CommonConstant.CURRENTTYPE) && !CommonConstant.CURRENTTYPE.equals("")){
		    		 goodis=id;
		    	 }
		     }
		     for(int i = 0 ; i < goodis ;i++){
		    	  CommonConstant.GOODSTYPE .remove(0);
		     }
		}
		
	}

	/**方法名称：getTypeBySearch()
	 * 方法说明：如果为类型爬取链接才会执行，否则不会执行该方法。类型获取url:"https://s.taobao.com/search?q=key&";
	 */
	@Override
	public void getTypeBySearch(Page page) {
		//爬取商品类别
		//使用搜索品牌爬取
  if(page.getHtml().xpath("//script").all().size()>0){
			List<String> allScript = page.getHtml().xpath("//script").all();
			int brandIndex = -1;
			for(int i = 0 ; i < allScript.size() ; i ++ ){
		              if(allScript.get(i).contains("g_page_config")){
		            	  brandIndex=i;
		              }
			}
			
		//JSON格式处理
		String brandTemp = allScript.get(brandIndex).trim().substring( allScript.get(brandIndex).indexOf("{"),allScript.get(brandIndex).indexOf("g_srp_loadCss"));
		String brand = brandTemp.substring(0,brandTemp.lastIndexOf(";"));
		Json brandJson = new Json(brand);
		
		//爬取品牌，将bid改为*可以爬取所有其他类型商品，目前暂停爬取品牌信息
		List<String> allCommon = brandJson.jsonPath("$.mods.nav.data.common[*]").all();
		int bid=  0;
		for(int i = 0 ; i < allCommon.size() ; i++){ 
			if(allCommon.get(i).contains("\"text\":\"品牌\"")){
				bid =i;
			}
		}
	    CommonConstant.GOODSTYPE = brandJson.jsonPath("$.mods.nav.data.common["+bid+"].sub[*].text").all();


	    //在品牌上添加品牌关键词，增加爬取商品准确率
	   for(int i = 0 ; i < CommonConstant.GOODSTYPE.size() ; i ++ ){
		   String orgType = CommonConstant.GOODSTYPE.get(i);
		   if(orgType.contains("/")){
			   CommonConstant.GOODSTYPE.set(i, orgType.substring(orgType.indexOf("/")+1,orgType.length())+"+"+CommonConstant.KEYWORD);
		   }else{
			   CommonConstant.GOODSTYPE.set(i, orgType+"+"+CommonConstant.KEYWORD);
		   }
	   }

	   //中途停下后处理
	     int goodis = 0;
	     for(int id = 0 ; id <CommonConstant.GOODSTYPE.size() ;id++ ){
	    	 if(CommonConstant.GOODSTYPE.get(id).equals(CommonConstant.CURRENTTYPE)){
	    		 goodis=id;
	    	 }
	     }
	     for(int i = 0 ; i < goodis ;i++){
	    	 CommonConstant.GOODSTYPE.remove(0);
	     }
		}
}

}
